import { Component, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
import { IntervalObservable } from "rxjs/observable/IntervalObservable";
import { GAService } from './shared/services/ga.service';

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>'//use this as master page of components    
  //styleUrls: ['./app.component.css']
})

/**
 * Main component
 */
export class AppComponent implements AfterViewInit, OnDestroy {
  private sub: any;
  private timer;

  constructor(private elm: ElementRef, private gaService: GAService) { }

  ngAfterViewInit() {
    this.heightChangeListener(this.onElementHeightChange);
  }

  ngOnDestroy() {
    this.stopTimer();
  }

  heightChangeListener(callback: Function): void {
    //parent element is the BODY element
    var parentElem = this.elm.nativeElement.parentNode;

    var lastHeight = parentElem.offsetHeight;
    this.timer = IntervalObservable.create(20)
      .subscribe(() => { 
        var newHeight = parentElem.offsetHeight;
        if (lastHeight != newHeight)
          callback(newHeight, this.gaService);
        lastHeight = newHeight;
      });
  }

  stopTimer() {
    if (this.timer !== undefined)
      this.timer.unsubscribe();
  }

  onElementHeightChange(height: number, service: GAService): void {
    service.resize(height);
  };
}